{extend name="common/__base"}

{block name="body"}
<form class="layui-form layui-form-pane">
    <input type="hidden" name="id" id="id" value="{$roleInfo.id}">
    <div class="layui-form-item">
        <label class="layui-form-label">角色名</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input" name="title" value="{$roleInfo.title}" id="title" lay-verify="required" placeholder="角色名">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">权限选择</label>
        <div class="layui-input-block">
            <div id="tree"></div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="submit">设置</button>
        </div>
    </div>
</form>
{/block}

{block name="js"}
<script>
    layui.use(['tree', 'jquery', 'form'], function () {
        let isClick = true,
            form = layui.form,
            tree = layui.tree,
            $ = layui.jquery,
            treeData = {$oneMenuList|raw},
            selectedTreeData = ("{$roleInfo.rules}").split(",");

        // 树状结构
        tree.render({
            elem: "#tree",
            data: treeData,
            showCheckbox: true,
            id: "tree"
        });
        tree.setChecked('tree', selectedTreeData);

        // 提交
        form.on("submit(submit)", function () {
            if (isClick) {
                isClick = false;
                let checkData = tree.getChecked("tree");
                let newData = [];
                for (let i = 0;i < checkData.length; i++) {
                    newData.push(checkData[i].id);
                    let children = checkData[i].children;
                    for (let j = 0;j < children.length;j++) {
                        newData.push(children[j].id);
                    }
                }
                if (newData.length == 0) {
                    isClick = true;
                    layer.msg("至少选择一个权限");
                } else {
                    $.post("{:url('admin/admin/editRole')}", {title: $("#title").val(), rules: newData.join(","), id: $("#id").val()}, function (res) {
                        if (res.code == 1) {
                            layer.msg(res.msg, function () {
                                location.reload();
                            });
                        } else {
                            isClick = true;
                            layer.msg(res.msg);
                        }
                    }, "json");
                }
            } else {
                layer.msg("不允许重复提交");
            }
            return false;
        });
    });
</script>
{/block}